package com.wing.web.exception;

import cn.hutool.core.util.ObjectUtil;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.web.utils.LocaleMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.nio.file.AccessDeniedException;

/**
 * 全局异常处理器
 *
 * @author
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private LocaleMessage localeMessage;

    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public JsonResult handleBusinessException(BusinessException e) {
        logger.error("business exception:{}", e);
        if (ObjectUtil.isNotEmpty(localeMessage.getMessage(e.getMessage()))) {
            return JsonResult.fail(e.getCode(), localeMessage.getMessage(e.getMessage()));
        } else {
            return JsonResult.fail(e.getCode(), e.getMessage());
        }
    }

    /**
     * 处理单个参数校验异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public JsonResult handleConstraintViolationException(ConstraintViolationException e) {
        StringBuffer sb = new StringBuffer();
        for (ConstraintViolation constraintViolation : e.getConstraintViolations()) {
            sb.append(constraintViolation.getMessage());
            break;
        }
        return JsonResult.fail(sb.toString());
    }

    /**
     * 处理对象校验异常
     */
    @ExceptionHandler(BindException.class)
    public JsonResult handleBindException(BindException e) {
        // ex.getFieldError():随机返回一个对象属性的异常信息。如果要一次性返回所有对象属性异常信息，则调用ex.getAllErrors()
        FieldError fieldError = e.getFieldError();
        String message;
        if (e.getFieldError() == null && e.getBindingResult().hasErrors()) {
            message = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        } else {
            message = fieldError.getDefaultMessage();
        }
        return JsonResult.fail(message);
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public JsonResult handlerNoFoundException(Exception e) {
        logger.error(e.getMessage(), e);
        return JsonResult.fail(JsonResult.Code.NO_FOUND_ERROR.getCode(), localeMessage.getMessage("member.login.invalid"));
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public JsonResult handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        logger.error(e.getMessage(), e);
        return JsonResult.fail(JsonResult.Code.METHOD_ERROR.getCode(), localeMessage.getMessage("common.request.method.error"));
    }

    @ExceptionHandler(AccessDeniedException.class)
    public JsonResult handleAccessDeniedException(Exception e) {
        return JsonResult.error(JsonResult.Code.ACCESS_DENIED);
    }

    @ExceptionHandler(Exception.class)
    public JsonResult handleException(Exception e) {
        logger.error(e.getMessage(), e);
        e.printStackTrace();
        return JsonResult.exception(localeMessage.getMessage("common.exception"));
    }

}
